<template>
  <div class="files">
    <el-upload
      action
      v-if="showEdit"
      :file-list="fileList"
      :multiple="true"
      :auto-upload="false"
      :on-change="onChange"
      :show-file-list="false"
    >
    <div slot="default"   class="avatar-uploader">
      <i class="el-icon-plus"></i>
    </div>
    </el-upload>
    <div class="file-list">
      <template v-if="!isPreview">
        <div class="file-item" v-for="(f, i) in fileList" :key="i">
          <div>{{ f.name }}</div>
          <el-link class="link" :underline="false" v-if="showEdit" icon="el-icon-error" @click.stop="handleRemove(f)">删除</el-link>
          <el-link  class="link" :underline="false" icon="el-icon-download" @click.stop="download(f)">下载</el-link>
        </div>
    </template>
      <div class="row" v-else>
          <div class="preview" v-for="(f, i) in fileList" :key="i">
            <el-image
              class="preview-img"
              :src="f.url"
              fit="contain"
              :preview-src-list="[f.url]"
            />
            <i class="el-icon-error canclick" v-if="showEdit" @click="handleRemove(f)"></i>
          </div>
        </div>
      <div v-if="!showEdit && fileList.length == 0">无</div>
    </div>
  </div>
</template>

<script>
import {UploadFile, DeleteHandleFile, SelectListFile, DownloadFile, GetFileBase64} from '@/api'
export default {
  props: {
    type: {
      type: Array, // img, pdf, file
      default () {
        return ['img']
      }
    },
    refId: {
      type: String,
      default: ''
    },
    bizType: {
      type: String,
      default: ''
    },
    isPreview: {
      type: Boolean,
      default: false
    },
    maxsize: {
      type: Number,
      default: 10
    },
    showEdit: {
      type: Boolean,
      default: true
    },
    autoUpload: { // 自动上报
      type: Boolean,
      default: false
    },
    filter: {
      type: Function,
      default: null
    }
  },
  data () {
    return {
      fileList: []
    }
  },
  mounted () {
    this.loadFiles()
  },
  methods: {
    download (f) {
      console.log(f)
      DownloadFile(f.name, {id: f.uid})
    },
    loadFiles () {
      this.fileList = []
      if (this.refId) {
        SelectListFile({
          refId: this.refId,
          type: this.bizType
        }).then(async res => {
          let data = res.data
          if (this.filter) {
            data = this.filter(data)
          }
          this.fileList = await Promise.all(data.map(async d => {
            let obj = {
              name: d.name,
              type: d.type,
              size: d.size,
              uid: d.id,
              status: 'finish'
            }
            if (this.isPreview) {
              let dataText = await GetFileBase64({
                id: d.id
              }).then(res => {
                console.log('GetFileBase64', res)
                return res.code === 20000 && res.data
              })
              obj.url =  `data:image/jpeg;base64,${dataText}`
            }
            return obj
          }))
        })
      }
    },
    verifyFile (file) {
      let result = false
      if (this.type.includes('file')) {
        if([
           'application/zip'
        ].includes(file.type)) {
          result = true
        }
      }
      if (this.type.includes('pdf')) {
        if([
           'application/pdf'
        ].includes(file.type)) {
          result = true
        }
      }
      if (this.type.includes('img')) {
        if([
          'image/jpg',
          'image/png',
          'image/jpeg',
          'image/bmp'
        ].includes(file.type)) {
          result = true
        }
      }
      return result
    },
    uploadFile ({refId, type}) {
      return Promise.all(this.fileList.filter(d => d.status != 'finish').map(d => {
          console.log('file', d)
         let formData = new FormData();
          formData.append('file', d.raw)
          formData.append('refId', refId)
          formData.append('type', type)
          formData.append('size', d.size)
          formData.append('name', d.name)
          return UploadFile(formData).then(res => {
            console.log('UploadFile', res)
            return res.code === 20000
          }).catch(() => false)
      }))
    },
    /**
     * 选择文件
     */
     onChange(file) {
      console.log(file);
      if (!this.beforeAvatarUpload(file.raw)) {
        return
      }
      file.url = URL.createObjectURL(file.raw)
      this.fileList.unshift(file);
      if (this.autoUpload && this.refId && this.bizType) {
        this.uploadFile({
          refId: this.refId, 
          type: this.bizType
        })
      }
    },
    handleRemove(file) {
      console.log(file, this.fileList);
      if (file.status === 'finish') {
        // 完成的
        DeleteHandleFile({
          id: file.uid
        }).then(res => {
          console.log('DeleteHandleFile', res);
        })
      }
      let index = this.fileList.findIndex(d => d.uid === file.uid)
      this.fileList.splice(index, 1)
    },
    beforeAvatarUpload(file) {
      console.log(file.type)
      if (!this.verifyFile(file)) {
        this.$message.error('不支持的文件格式!')
        return false;
      }
      const isMaxOk = file.size / 1024 / 1024 < this.maxsize

      if (!isMaxOk) {
        this.$message.error(`上传文件大小不能超过${this.maxsize}MB!`)
      }
      return isMaxOk
    }
  }
}
</script>

<style lang="scss" scoped>
.files {
  .avatar-uploader {
    height: 80px;
    width: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    border-radius: 5px;
    border: 1px solid #e1e1e2;
    i {
      font-size: 30px;
    }
  }
  .file-list {
    display: flex;
    flex-direction: column;
   
    .file-item {
      display: flex;
      flex-direction: row;
      align-items: center;
      .link {
        visibility: hidden;
        margin-left: 20px;
        &:hover {
            color: red;
        }
      }
      &:hover {
        color: #999;
        .link {
          cursor: pointer;
          visibility: visible;
        }
      }
     
    }
  }
}
.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  overflow-y: auto;
}
.preview {
  position: relative;
  width: 150px;
  height: 100px;
  border: 1px solid #ccc;
  margin-right: 10px;
  margin-top: 10px;
  box-sizing: border-box;
  .preview-img {
    width: 100%;
    height: 100%;
    object-fit: contain;
  }
  .el-icon-error {
    position: absolute;
    right: 5px;
    top: 5px;
    font-size: 20px;
    color: #ccc;
    cursor: pointer;
    &:hover {
      color: red;
    }
  }
}
</style>